package qs.openxt.libs.plugins;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import qs.openxt.libs.R;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.voice.VoiceActivity;

/**
 * 语音识别
 * @author 颖杰_2
 *
 */
public class VoicePlugins extends CordovaPlugin{
	private CallbackContext callbackContext;
	public static final int RETURNTYPE_VOICE = 1;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:{
					callbackContext.success((String)msg.obj);
					break;
				}
			default:
				break;
			}
		};
	};
	
	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		if ("doStartRecognizerApp".equals(action)) {
			if(!ActivityUtil.isNetworkAvailable(cordova.getActivity())){
				Toast.makeText(cordova.getActivity(), cordova.getActivity().getString(R.string.isNetworkAvailable), Toast.LENGTH_LONG).show();
				return false;
			}
			Intent intent = new Intent();
			intent.setClass(cordova.getActivity(), VoiceActivity.class);
			cordova.startActivityForResult(VoicePlugins.this, intent, RETURNTYPE_VOICE);
			return true;
		}
		return false;
	}
	
	public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		
		if (requestCode == RETURNTYPE_VOICE && resultCode == Activity.RESULT_OK) {
			String code = intent.getExtras().getString("code");
			
			Message message = new Message();
			message.what = 1;
			message.obj = code;
			mHandler.sendMessage(message);
		}
	}
}
